package com.sxt.system.service.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxt.system.constast.Constast;
import com.sxt.system.domain.Dept;
import com.sxt.system.domain.User;
import com.sxt.system.mapper.RoleMapper;
import com.sxt.system.mapper.UserMapper;
import com.sxt.system.service.IDeptService;
import com.sxt.system.service.IUserService;
import com.sxt.system.utils.DataGridView;
import com.sxt.system.utils.FileUploadAndDownUtil;
import com.sxt.system.utils.MD5Utils;
import com.sxt.system.vo.UserVO;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 俊哥
 * @since 2019-11-08
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService,ApplicationContextAware  {

	@Autowired
	@Lazy
	private IDeptService deptService;
	
	@Autowired
	private RoleMapper roleMapper;
	
	
	/**
	 * 声明日志输入对象
	 */
	private Log log = LogFactory.getLog(UserServiceImpl.class);
	
	@Override
	public User queryUserByUserName(String username) {
		UserMapper userMapper = this.getBaseMapper();
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		if(null == username) {
			log.error("用户登录名不能为空");
			throw new RuntimeException("用户登录名不能为空");
		}
		queryWrapper.eq("loginname", username);
		User user = userMapper.selectOne(queryWrapper);
		return user;
	}

	@Override
	public User getById(Serializable id) {
		return super.getById(id);
	}

	@Override
	public DataGridView loadAllUser(UserVO userVO) {
		Page<User> page = new Page<>(userVO.getPage(),userVO.getLimit());
		QueryWrapper<User> qw = new QueryWrapper<User>();
		qw.eq( "type", Constast.USER_TYPE_NORMAL);
		qw.eq(userVO.getDeptid()!=null,"deptid", userVO.getDeptid());
		qw.and(StringUtils.isNoneBlank(userVO.getName()), new Consumer<QueryWrapper<User>>() {
			
			@Override
			public void accept(QueryWrapper<User> t) {
				t.like(StringUtils.isNotBlank(userVO.getName()), "name", userVO.getName()).or()
				.like(StringUtils.isNotBlank(userVO.getName()), "loginname", userVO.getName());
			}
		});
		qw.like(StringUtils.isNotBlank(userVO.getAddress()), "address", userVO.getAddress());
		qw.orderByAsc("hiredate");
		
		this.getBaseMapper().selectPage(page, qw);
		List<User> list = page.getRecords();
		for (User user : list) {
			Integer deptid = user.getDeptid();
			Integer mgr = user.getMgr();
			//根据ID去查询部门
			Dept dept = deptService.getById(deptid);
			user.setDeptname(dept.getTitle());
			
			//根据领导ID去查询领导名称
			if(null != mgr) {//如果直接使用this那么缓存切面不生效
				IUserService userService = content.getBean(IUserService.class);
				User user2 = userService.getById(mgr);
				user.setLeadername(user2.getName());
			}
		}
		return new DataGridView(page.getTotal(),page.getRecords());
		
	}

	private ApplicationContext content;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.content = applicationContext;
	}

	@Override
	public Integer queryUserMaxOrderNum() {
		return this.getBaseMapper().queryUserMaxOrderNum();
	}

	@Override
	public List<User> queryUserByDeptId(Integer deptid) {
		QueryWrapper<User> qw = new QueryWrapper<User>();
		if(null == deptid) {
			return null;
		}else {
			qw.eq("type", Constast.USER_TYPE_NORMAL);
			qw.eq(deptid!=null, "deptid", deptid);
			return this.getBaseMapper().selectList(qw);
		}
	}

	@Override
	public User addUser(User user) {
		this.getBaseMapper().insert(user);
		return user;
	}

	@Override
	public User updateUser(User user) {
		this.getBaseMapper().updateById(user);
		return user;
	}

	@Override
	public boolean removeById(Serializable id) {
		//根据用户ID删除用户和角色的关系
		roleMapper.deleteUserRoleByUserId(id);
		return super.removeById(id);
	}

	@Override
	public boolean removeByIds(Collection<? extends Serializable> idList) {
		for (Serializable id : idList) {
			this.roleMapper.deleteUserRoleByUserId(id);
		}
		return super.removeByIds(idList);
	}

	@Override
	public void resetUserPwd(Integer id) {
		User user = new User();
		user.setId(id);
		user.setSalt(MD5Utils.getSalt());
		user.setPwd(MD5Utils.md5(Constast.USER_DEFAULT_PWD, user.getSalt(), 2));
		this.getBaseMapper().updateById(user);
	}

	@Override
	public void saveUserRole(Integer userId, Integer[] rids) {
		//根据用户Id删除sys_role_user里面的数据
		this.roleMapper.deleteUserRoleByUserId(userId);
		if(rids!=null&&rids.length>0) {
			for (Integer rid : rids) {
				this.getBaseMapper().saveUserRole(userId,rid);
			}
		}
	}

	@Override
	public void changePwd(Integer id, String newPwd) {
		User user = new User();
		user.setId(id);
		user.setSalt(MD5Utils.getSalt());
		user.setPwd(MD5Utils.md5(newPwd, user.getSalt(), 2));
		this.getBaseMapper().updateById(user);
	}

	@Value("${upload.upload-root-path}")
	private String uploadRootPath = "D:/upload";
	
	@Autowired
	private HttpServletRequest request;
	
	@Override
	public void changeUser(User user) {
		//1处理图片
		String imgpath = user.getImgpath();
		if(!imgpath.equals(Constast.USER_DEFAULT_IMAGE)) {
			//修改了图片
			if(imgpath.endsWith("_temp")) {
				String path = FileUploadAndDownUtil.changeFileName(uploadRootPath, imgpath);
				user.setImgpath(path);
				//删除原来的图片
				User sessionUser = (User) request.getSession().getAttribute("user");
				FileUploadAndDownUtil.deleteFile(uploadRootPath, sessionUser.getImgpath());
				//替换session里面的图片
				sessionUser.setImgpath(path);
				request.getSession().setAttribute("user", sessionUser);
			}
		}
		this.getBaseMapper().updateById(user);
	}

	
	
}
